package cn.derry.server;

import cn.derry.domain.Account;
import cn.derry.domain.Message;
import cn.derry.util.RedisUtil;
import cn.derry.util.ResponseUtil;
import cn.derry.util.SerializerUtil;
import com.alibaba.fastjson.JSON;
import redis.clients.jedis.Jedis;

import java.util.*;
import java.util.List;

/**
 * @author MangoDai
 * @decription 聊天控制类
 * @date 2017/12/20
 **/
public class ChatServer {


    public static boolean saveChatRecord(String from, String to, String message) {
        Jedis jedis = RedisUtil.getJedis();
        byte[] serialize = SerializerUtil.serialize(new Message(from, to, message));
        jedis.zadd(generateZsetKey(from, to).getBytes(), (double) System.currentTimeMillis(), serialize);
        RedisUtil.release(jedis);
        return true;
    }

    public static List<Message> getChatRecord(String from, String to) {
        Jedis jedis = RedisUtil.getJedis();
        Set<byte[]> zrange = jedis.zrange(generateZsetKey(from, to).getBytes(), 0, -1);
        ArrayList<Message> objects = new ArrayList<>(zrange.size());
        Iterator<byte[]> iterator = zrange.iterator();
        while (iterator.hasNext()) {
            Object object = SerializerUtil.unserizlize(iterator.next());
            if (object instanceof Message) {
                objects.add((Message) object);
            }
        }
        RedisUtil.release(jedis);
        return objects;
    }


    /**
     * 按照他们的学号来生成键，表示他们的聊天记录
     *
     * @param from
     * @param to
     * @return
     */
    public static String generateZsetKey(String from, String to) {
        if (from.compareTo(to) > 0) {
            return from + to;
        } else {
            return to + from;
        }
    }
}
